package com.itxiuyixiu.volunteer.component;

import com.itxiuyixiu.entity.enums.AccountState;
import com.itxiuyixiu.entity.enums.AuthorityType;
import com.itxiuyixiu.entity.mapper.AdminReaderMapper;
import com.itxiuyixiu.entity.mapper.AdminWriterMapper;
import com.itxiuyixiu.entity.model.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author 黄磊
 * @date 2020/5/2
 */
@Component
public class AdminRegisterComponent implements ApplicationRunner {
    @Resource
    private AdminReaderMapper adminReaderMapper;
    @Resource
    private AdminWriterMapper adminWriterMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Optional<Admin> adminOptional = adminReaderMapper.findAdminByUsername("admin");
        if (!adminOptional.isPresent()) {
            Admin admin = new Admin();
            admin.setUsername("admin");
            admin.setPassword(passwordEncoder.encode("123456"));
            admin.setAuthorities(AuthorityType.ROLE_ADMIN);
            admin.addAuthority(AuthorityType.BASIC_ADMIN_AUTHORITY);
            admin.setNickName("网站运营者");
            admin.setAdminEmail("huang147753@qq.com");
            admin.setAccountState(AccountState.PASSED);
            adminWriterMapper.saveAdmin(admin);
        }
    }
}
